package szk.exam.controller;
/*
 * @Description:
 * @Author: 山志凯
 * @Date: 2021-06-16
 * @Time: 09:36
 */

import szk.exam.pojo.Student;
import szk.exam.service.StuService;
import szk.exam.service.impl.StuServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(value = "/stu/login")
public class StuController extends HttpServlet {
    private StuService stuService = new StuServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取浏览器请求的参数：用户名和密码
        String stuName = req.getParameter("stuName");
        String stuPwd = req.getParameter("stuPwd");
        //调用service层的方法login（）验证用户身份
        boolean flag = false;
        try {
            flag = stuService.login(stuName, stuPwd);
            if (flag) {
                //验证通过 用户名和密码都 对
                //1、将登录用户的信息封装到一个Student类的javabean中
                Student loginInfo = new Student();
                loginInfo.setStuName(stuName);
                loginInfo.setStuPwd(stuPwd);
                //2、将javabean user存入到session
                req.getSession().setAttribute("loginInfo", loginInfo);
                //3、调用service层方法getAll（）获取用户表中所有用户信息
                List<Student> student = stuService.getAll();
                //3、请求转发页面 userList.jsp
                req.setAttribute("student",student);
                req.getRequestDispatcher("/jsp/userList.jsp").forward(req, resp);

            } else {
                resp.getWriter().write("用户名或密码错误!!");
            }
        } catch (SQLException s) {
            s.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
